package com.gupaoedu.mvcframework.v1.servlet;

import com.gupaoedu.mvcframework.annotation.GPAutowired;
import com.gupaoedu.mvcframework.annotation.GPController;
import com.gupaoedu.mvcframework.annotation.GPRequestMapping;
import com.gupaoedu.mvcframework.annotation.GPService;
import com.sun.org.slf4j.internal.Logger;
import com.sun.org.slf4j.internal.LoggerFactory;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class GPDispatcherServlet extends HttpServlet {

    private final static Logger logger = LoggerFactory.getLogger(GPDispatcherServlet.class);

    private final Map<String, Object> mapping = new HashMap<String, Object>();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            doDispatch(req, resp);
        } catch (Exception e) {
            resp.getWriter().write("500 Exception " + Arrays.toString(e.getStackTrace()));
        }
    }

    private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        String url = req.getRequestURI();
        String contextPath = req.getContextPath();
        url = url.replace(contextPath, "").replaceAll("/+", "/");
        if (!this.mapping.containsKey(url)) {
            resp.getWriter().write("404 Not Found!!");
            return;
        }
        Method method = (Method) this.mapping.get(url);
        Map<String, String[]> params = req.getParameterMap();
        method.invoke(this.mapping.get(method.getDeclaringClass().getName()), new Object[]{req, resp, params.get("name")[0]});
    }

    @Override
    public void init(ServletConfig config) throws ServletException {
        InputStream is = null;
        try {
            Properties configContext = new Properties();
            is = this.getClass().getClassLoader().getResourceAsStream(config.getInitParameter("contextConfigLocation"));
            configContext.load(is);
            String scanPackage = configContext.getProperty("scanPackage");
            //扫描包 初始化map容器 key是java类名
            doScanner(scanPackage);
            //遍历初始化后的map容器
            for (String className : mapping.keySet()) {
                if (!className.contains(".")) {
                    continue;
                }
                //java类class
                Class<?> clazz = Class.forName(className);
                //如果类上含有Controller注解
                if (clazz.isAnnotationPresent(GPController.class)) {
                    mapping.put(className, clazz.newInstance());
                    String baseUrl = "";
                    //如果类上含有RequestMapping注解
                    if (clazz.isAnnotationPresent(GPRequestMapping.class)) {
                        //获取GPRequestMapping注解
                        GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
                        //获取注解的value baseurl就是url
                        baseUrl = requestMapping.value();
                    }
                    //获取类的所有方法
                    Method[] methods = clazz.getMethods();
                    //遍历类的所有方法
                    for (Method method : methods) {
                        //如果方法不含有GPRequestMapping 不做处理
                        if (!method.isAnnotationPresent(GPRequestMapping.class)) {
                            continue;
                        }
                        //获取方法上的GPRequestMapping注解
                        GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
                        //拼接访问路径
                        String url = (baseUrl + "/" + requestMapping.value()).replaceAll("/+", "/");
                        //key:访问路径 value:方法
                        mapping.put(url, method);
                        System.out.println("Mapped " + url + "," + method);
                        logger.debug("=======Mapped:{},method:{}======", url, method);
                    }
                } else if (clazz.isAnnotationPresent(GPService.class)) {
                    //如果类上含有GPService注解 获取GPService注解
                    GPService service = clazz.getAnnotation(GPService.class);
                    //获取注解的value
                    String beanName = service.value();
                    //如果注解的value是空
                    if ("".equals(beanName)) {
                        //beanName是当前类名
                        beanName = clazz.getName();
                    }
                    //当前类实例
                    Object instance = clazz.newInstance();
                    //key:类名 value:类实例
                    mapping.put(beanName, instance);
                    //遍历当前类的所有接口
                    for (Class<?> i : clazz.getInterfaces()) {
                        //key:类名 value:接口
                        mapping.put(i.getName(), instance);
                    }
                } else {
                    continue;
                }
            }

            for (Object object : mapping.values()) {
                if (object == null) {
                    continue;
                }
                Class clazz = object.getClass();
                //如果是Controller
                if (clazz.isAnnotationPresent(GPController.class)) {
                    //获取某个类的所有声明的字段
                    Field[] fields = clazz.getDeclaredFields();
                    for (Field field : fields) {
                        //如果字段不含有GPAutowired注解 不做处理
                        if (!field.isAnnotationPresent(GPAutowired.class)) {
                            continue;
                        }
                        //获取GPAutowired注解
                        GPAutowired autowired = field.getAnnotation(GPAutowired.class);
                        //获取注解的value值
                        String beanName = autowired.value();
                        if ("".equals(beanName)) {
                            beanName = field.getType().getName();
                        }
                        //强制访问
                        field.setAccessible(true);
                        try {
                            field.set(mapping.get(clazz.getName()), mapping.get(beanName));
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception e) {
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        System.out.print("GP MVC Framework is init");
        logger.debug("GP MVC Framework is init");
    }

    /**
     * 扫描指定路径下的类 初始化进容器
     *
     * @param scanPackage 包路径
     */
    private void doScanner(String scanPackage) {
        //获取路径url
        URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.", "/"));
        //根据路径生成一个文件
        File classDir = new File(url.getFile());
        //遍历路径下的所有文件
        for (File file : classDir.listFiles()) {
            if (file.isDirectory()) {
                //如果是文件夹 递归扫描
                doScanner(scanPackage + "." + file.getName());
            } else {
                //如果不是java类 不做处理
                if (!file.getName().endsWith(".class")) {
                    continue;
                }
                //获取java类名
                String clazzName = (scanPackage + "." + file.getName().replace(".class", ""));
                //将类初始化容器中
                mapping.put(clazzName, null);
            }
        }
    }
}